package com.example.springsecurity.handler;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
public class LoginFailureHandler extends SimpleUrlAuthenticationFailureHandler {

    private Logger logger = LoggerFactory.getLogger(getClass());

    /**
     *
     * @param request
     * @param response
     * @param exception : 登陆失败的原因
     */
    @Override
    public void onAuthenticationFailure(HttpServletRequest request,
                                        HttpServletResponse response,
                                        AuthenticationException exception) throws IOException {
        //exception.getMessage() : 返回登陆失败的原因
        logger.error("登录错误 : {}",exception.getMessage());
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);//400状态码
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);//设置请求头 : application/json;charset=UTF-8
        //创建输出对象
        PrintWriter writer = response.getWriter();
        if ("Bad credentials".equals(exception.getMessage())) {
            writer.write("密码不正确");
        }else {
            writer.write(exception.getMessage());
        }
        writer.flush();
        writer.close();
    }

}
